<template>
  <!-- <div class="demo-container" v-html="svgstr"></div> -->
  <div ref="svgContainer" v-html="svgstr" class="svg-container"></div>

</template>

<script>
export default {
  data() {
    return {
      svgstr: ''
    }
  },
  mounted() {
    // const svg = this.$d3.select('body').append('svg')
    //   .attr('width', '100%')
    //   .attr('height', '100%');
    this.addZoomAndPan();

  },
  methods: {
    addZoomAndPan() {
      const svgContainer = this.$refs.svgContainer;

      // 获取 SVG 元素
      const svgElement = svgContainer.querySelector("svg");

      // 使用 D3.js 创建缩放行为
      const zoom = this.$d3.zoom()
        .scaleExtent([0.5, 10]) // 限制缩放范围
        .on("zoom", (event) => {
          // 在缩放和平移时应用变换
          this.$d3.select(svgElement).attr("transform", event.transform);
        });

      // 使 SVG 容器可缩放
      this.$d3.select(svgContainer).call(zoom);

      // 设置缩放中心为 SVG 的中心点
      const bbox = svgElement.getBBox();
      const width = bbox.width;
      const height = bbox.height;
      const centerX = width / 2;
      const centerY = height / 2;

      svgElement.setAttribute("viewBox", `${bbox.x} ${bbox.y} ${width} ${height}`);
      svgElement.setAttribute("preserveAspectRatio", "xMidYMid meet");

      // 更新缩放中心
      this.$d3.select(svgContainer)
        .call(zoom.transform, this.$d3.zoomIdentity.translate(centerX, centerY).scale(1));
    }
  }

}
</script>

<style>
.svg-container {
  width: 100%;
  height: 100vh;
  /* 让容器占满整个视口 */
  overflow: hidden;
  /* 隐藏溢出部分 */
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f0f0;
}
</style>